﻿
CREATE FUNCTION dbo.NumberToText
(	@Num varchar(50)
)RETURNS varchar(1024)
AS
BEGIN
DECLARE @ID numeric,@Tri varchar(3),@Out varchar(512),@Out3 varchar(512)
DECLARE @Cents varchar(50)

SELECT @Cents = PARSENAME(@Num,1),@Num = PARSENAME(@Num,2), @Out = ''
IF @Num IS NULL SELECT @Num = @Cents, @Cents = NULL

WHILE LEN(@Num) > 0 BEGIN
	SELECT @Tri =	RIGHT(@Num,3),@Num = LEFT(@Num,dbo.MaxNum(0,LEN(@Num)-3)),@Out3 = ''
	SELECT @Out3 = dbo.DigitToText(RIGHT(@Tri,2),'','') + @Out3
	IF @Out3 > '' SET @Tri = LEFT(@Tri,dbo.MaxNum(0,LEN(@Tri)-2))
	ELSE BEGIN
		SELECT @Out3 = dbo.DigitToText(RIGHT(@Tri,1)   ,'','')  + @Out3,@Tri = LEFT(@Tri,dbo.MaxNum(0,LEN(@Tri)-1))
		SELECT @Out3 = dbo.DigitToText(RIGHT(@Tri,1)*10,'',' ') + @Out3,@Tri = LEFT(@Tri,dbo.MaxNum(0,LEN(@Tri)-1))
	END
	SELECT @Out3 = dbo.DigitToText(RIGHT(@Tri,1),'',' hundred ') + @Out3
	SET @Out3 = @Out3 + dbo.DigitToText(@ID,' ',' ')
	SET @Out = @Out3 + @Out
	SET @ID = ISNULL(@ID,1)*1000
END

/*
DECLARE @Teen char(1)
WHILE LEN(@Num) > 0 BEGIN
	SELECT @Tri =	RIGHT(@Num,3),@Num = LEFT(@Num,dbo.MaxNum(0,LEN(@Num)-3)),@Out3 = '',@Teen = ''
	SELECT @Out3 = dbo.DigitToText(RIGHT(@Tri,1),'','') + @Out3,@Teen = RIGHT(@Tri,1),@Tri = LEFT(@Tri,dbo.MaxNum(0,LEN(@Tri)-1))
	IF RIGHT(@Tri,1) <> 1	OR @Out3 = '' SET @Teen = '' ELSE SET @Out3 =  ''
	SELECT @Out3 = dbo.DigitToText(RIGHT(@Tri,1)*10+@Teen,'',' ') + @Out3,@Tri = LEFT(@Tri,dbo.MaxNum(0,LEN(@Tri)-1))
	SELECT @Out3 = dbo.DigitToText(RIGHT(@Tri,1),'',' hundred ') + @Out3
	SET @Out3 = @Out3 + dbo.DigitToText(@ID,' ',' ')
	SET @Out = @Out3 + @Out
	SET @ID = ISNULL(@ID,1)*1000
END
*/
RETURN @Out + ISNULL(' and '+@Cents+'/'+CONVERT(varchar,POWER(10,LEN(@Cents))),'')
END

